var config = require('../../config.js')
var http = require('../../utils/httpHelper.js')
Page({
  data: {
    allShops:[],
    isLogin:false,
    sumPrice:0,
    timer:{},
    shopPage:{
      current:1,
      pageSize:10,
			total:0
    }
  },
  onLoad: function () {
    let userInfo = wx.getStorageSync('user');
    if (userInfo!=null&&userInfo!=undefined&&userInfo!={}&&userInfo!='') {
      this.setData({
        isLogin:true
      })
    }
    wx.openSetting({
      success: function(res) {
        if (res.authSetting['scope.userLocation'] == true) {
          wx.showToast({
            title: '授权成功',
            icon: 'success',
            duration: 1000
          });
        }else {
          wx.showToast({
            title: '授权失败',
            icon: 'none',
            duration: 1000
          });
        }
      }
    });
  },
  onShow:function(){
    let userInfo = wx.getStorageSync('user');    
    if (userInfo!=null&&userInfo!=undefined&&userInfo!={}&&userInfo!='') {
      this.setData({
        isLogin:true
      })
    }
    this.onChangeLocation();
  },
  onReachBottom(){
    if(this.timer != null){
      clearTimeout(this.timer)
    }
    this.timer = setTimeout(()=>{
      this.getMoreData();
    },1000)
  },
  async getMoreData() {
    let dataWz = await this.authorizedPositioningPromise();
    if(dataWz){
      var that = this;
      that.data.shopPage.current++;
      that.getShopAllList(dataWz,function(list){
        let yList = that.data.allShops;
        yList = yList.concat(list);
        that.setData({allShops:yList});
      })
    }
  },
  getShopAllList:function(dataWz,callback){
    var that = this;
    http.httpPost(config.clubApi.getShopAllList,{
      appid: config.APPID,
      pageNo:that.data.shopPage.current,
      pageSize:that.data.shopPage.pageSize,
      lng: dataWz.longitude,
      lat: dataWz.latitude
    },function (res){        
      if(res.code == '200'){
        var list = res.data.pageData;
        typeof callback == "function" && callback(list)
      }
    });
  },
  toDetail:function(e){
    var idParam = e.currentTarget.dataset.id;
    var idParamAry = idParam.split(',');
    if (idParamAry[2]>0) {
      wx.navigateTo({
        url: '../shop/detail/index?id='+idParamAry[0]+'&shopName='+idParamAry[1]
      })
    }else {
      wx.showToast({
        title: '没有商品可以展示',
        icon: 'success',
        duration: 1000
      });
    }
  },
  appointment:function(e){
    if (this.data.isLogin&&wx.getStorageSync('user')) {
      var idParam = e.currentTarget.dataset.id;
      var idParamAry = idParam.split(',');
      wx.navigateTo({ 
        url: '/pages/shop/appointment/index?id='+idParamAry[0]+'&shopName='+idParamAry[1]
      });
    }else {
      wx.switchTab({ url: '/pages/user/index' });
    }
  },
  openLocation:function(e){
    var idParam = e.currentTarget.dataset.id;
    var idParamAry = idParam.split(',');
    wx.openLocation({
      longitude: Number(idParamAry[0]),
      latitude: Number(idParamAry[1]),
      name: idParamAry[2],
      address: idParamAry[3]+idParamAry[4]
    })
  },
  async onChangeLocation(){
    let dataWz = await this.authorizedPositioningPromise();
    if(dataWz){
      var that = this;
      that.getShopAllList(dataWz,function(list){
        that.setData({allShops:list});
      })
    }
  },
  //	授权定位
  async authorizedPositioningPromise() {
    return new Promise((resolve, reject) => {
      wx.getSystemInfo({
        success({locationEnabled,locationAuthorized}) {
          // locationEnabled 判断手机定位服务是否开启
          // locationAuthorized 判断定位服务是否允许微信授权
          if (!locationEnabled && !locationAuthorized) {
            // GPS未开启 与 GPS未给微信授权定位服务
            reject("GPSnotOpen");
          } else if (locationEnabled && !locationAuthorized) {
            // GPS已开启 与 GPS未给微信授权定位服务
            reject("GPSauthorization");
          } else if (locationEnabled && locationAuthorized) {
            //GPS已开启 与 GPS已给微信授权定位服务 判断微信小程序位置信息是否开启
            wx.authorize({
              scope: "scope.userLocation",
              success() {
                // 微信小程序位置信息已开启
                wx.getLocation({
                  type: "gcj02",
                  isHighAccuracy: true,
                  success: function(res) {
                    // latitude; 纬度
                    // longitude; 经度
                    resolve({
                      latitude: res.latitude,
                      longitude: res.longitude
                    });
                  }
                });
              },
              fail() {
                // 微信小程序位置信息未开启
                reject("weixinPositionNotOpen");
              }
            })
          }
        },
        fail(err) {
          console.error("err===>>>",err);
          let reg = /request:fail/;
          if (reg.test(err.errMsg)) {
            // 无网络
            reject("noNetWork");
          } else {
            // 请求超时'
            reject("requestTimeOut");
          }
        }
      })
    });
  }
})